/*
 * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/module-main/src/main/java/org/apache/http/message/BasicNameValuePair.java $
 * $Revision: 604625 $
 * $Date: 2007-12-16 06:11:11 -0800 (Sun, 16 Dec 2007) $
 *
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package com.koushikdutta.ion.sample;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.utils.net.Uri;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Uri 处理工具类
 */
public class UriUtils {
    private static final String SCHEME_DATA = "dataability";
    private static final String SCHEME_FILE = "file";
    private static final String SCHEME_HTTP = "http";
    private static final String SCHEME_HTTPS = "https";
    private static final Logger logger = Logger.getLogger(UriUtils.class.getName());

    /**
     * Uri转ImageSource
     *
     * @param context 上下文
     * @param uri uri
     * @return 返回ImageSource
     */
    public static ImageSource uriToImageSource(Context context, Uri uri) {
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        if (isDataMediaUri(uri)) {
            return ImageSource.create(uriToInputStream(context, uri), options);
        } else if (isResourceUri(context, uri)) {
            return ImageSource.create(uriToResource(context, uri), options);
        } else if (isNetWorkUri(uri)) {
            return null;
        } else if (isFileUri(uri)) {
            return ImageSource.create(uriToFileInputStream(uri), options);
        } else if (isAssertUri(uri)) {
            return ImageSource.create(uriRawFile(context, uri), options);
        } else {
            return null;
        }
    }

    /**
     * 判断是否是media uri
     *
     * @param uri dataability:///media/***
     * @return 结果
     */
    private static boolean isDataMediaUri(Uri uri) {
        if (uri.getDecodedPathList() != null) {
            if (uri.getDecodedPathList().size() > 0) {
                return uri.getScheme().equals(SCHEME_DATA) && uri.getEncodedAuthority().isEmpty() && uri.getDecodedPathList().get(0).equals("media");
            }
        }
        return false;
    }

    /**
     * 判断是否是Assert 目录文件
     *
     * @param uri dataability:///resources/rawfile/...
     * @return 返回结果
     */
    private static boolean isAssertUri(Uri uri) {
        if (uri.getDecodedPathList() != null) {
            if (uri.getDecodedPathList().size() > 2) {
                return uri.getScheme().equals(SCHEME_DATA)
                        && uri.getEncodedAuthority().isEmpty()
                        && uri.getDecodedPathList().get(0).equals("resources")
                        && uri.getDecodedPathList().get(1).equals("rawfile");
            }
        }
        return false;
    }


    /**
     * 判断是否是资源文件uri
     *
     * @param context 上下文
     * @param uri     dataability://bundleName/id
     * @return 结果
     */
    private static boolean isResourceUri(Context context, Uri uri) {
        return uri.getScheme().equals(SCHEME_DATA) && uri.getDecodedAuthority().equals(context.getBundleName());
    }

    /**
     * 判断是否是网络uri
     *
     * @param uri http://www.***.com or https://www.***.com
     * @return 结果
     */
    private static boolean isNetWorkUri(Uri uri) {
        return uri.getScheme().equals(SCHEME_HTTP) || uri.getScheme().equals(SCHEME_HTTPS);
    }

    /**
     * 判断是否是文件uri
     *
     * @param uri file://...
     * @return 是与否
     */
    private static boolean isFileUri(Uri uri) {
        return uri.getScheme().equals(SCHEME_FILE);
    }

    private static FileInputStream uriToFileInputStream(Uri uri) {
        try {
            File file = new File(uri.getDecodedPath());
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
            logger.log(Level.INFO, "IOException in test");
        }
        return null;
    }

    private static FileDescriptor uriToInputStream(Context context, Uri uri) {
        try {
            return DataAbilityHelper.creator(context).openFile(uri, "r");
        } catch (DataAbilityRemoteException | FileNotFoundException e) {
            logger.log(Level.INFO, "IOException in test");
        }

        return null;
    }

    private static Resource uriToResource(Context context, Uri uri) {
        try {
            return context.getResourceManager().getResource(Integer.parseInt(uri.getLastPath()));
        } catch (NotExistException | IOException e) {
            logger.log(Level.INFO, "IOException in test");
        }
        return null;
    }

    private static Resource uriRawFile(Context context, Uri uri) {
        try {
            RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry("resources/rawfile/" + uri.getLastPath());
            return rawFileEntry.openRawFile();
        } catch (IOException e) {
            logger.log(Level.INFO, "IOException in test");
        }
        return null;
    }
}
